import { Card, Form, Input, InputNumber, Button, message, Table, Tag, Modal, FloatButton, Popconfirm, Select } from 'antd';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getAppliedCourses, applyCourse, cancelApplication, getMyCourses } from '../../api/teacher';
import { FileAddOutlined } from '@ant-design/icons';
import { useState } from 'react';
import type { Course, TimeSlot } from '../../types';

export default function ApplyCourse() {
  const queryClient = useQueryClient();
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);

  const { data: appliedCourses = [] } = useQuery({ 
    queryKey: ['teacher', 'applied-courses'], 
    queryFn: getAppliedCourses 
  });

  const { data: myCourses = [] } = useQuery({ 
    queryKey: ['teacher', 'my-courses'], 
    queryFn: getMyCourses 
  });

  const applyCourseMutation = useMutation({
    mutationFn: applyCourse,
    onSuccess: () => {
      message.success('课程申请提交成功！');
      form.resetFields();
      setIsModalOpen(false);
      queryClient.invalidateQueries({ queryKey: ['teacher', 'applied-courses'] });
    },
    onError: () => {
      message.error('提交失败，请重试');
    },
  });

  const cancelApplicationMutation = useMutation({
    mutationFn: cancelApplication,
    onSuccess: () => {
      message.success('申请已取消');
      queryClient.invalidateQueries({ queryKey: ['teacher', 'applied-courses'] });
    },
    onError: () => {
      message.error('取消失败，请重试');
    },
  });

  const handleOpenModal = () => {
    form.resetFields();
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  // 星期选项
  const weekOptions = [
    { label: '周一', value: '周一' },
    { label: '周二', value: '周二' },
    { label: '周三', value: '周三' },
    { label: '周四', value: '周四' },
    { label: '周五', value: '周五' },
    { label: '周六', value: '周六' },
    { label: '周日', value: '周日' },
  ];

  // 节次选项（节次到时间的映射）
  const periodOptions = [
    { label: '1-2节', value: '1-2', time: '08:00-10:00' },
    { label: '3-4节', value: '3-4', time: '10:00-12:00' },
    { label: '5-6节', value: '5-6', time: '14:00-16:00' },
    { label: '7-8节', value: '7-8', time: '16:00-18:00' },
    { label: '9-10节', value: '9-10', time: '19:00-21:00' },
  ];

  // 将时间字符串转换为时间段对象
  const parseTimeStringToSlot = (timeStr: string, startWeek: number, endWeek: number): TimeSlot | null => {
    // 匹配格式：周一 14:00-16:00
    const pattern = /(周[一二三四五六日]|星期[一二三四五六日])\s+(\d{1,2}):(\d{2})-(\d{1,2}):(\d{2})/;
    const match = timeStr.match(pattern);
    if (!match) return null;

    const dayMap: Record<string, number> = {
      '周一': 1, '周二': 2, '周三': 3, '周四': 4, '周五': 5, '周六': 6, '周日': 7,
      '星期一': 1, '星期二': 2, '星期三': 3, '星期四': 4, '星期五': 5, '星期六': 6, '星期日': 7,
    };

    const dayStr = match[1];
    const dayOfWeek = dayMap[dayStr] || 1;
    const start = `${match[2].padStart(2, '0')}:${match[3]}`;
    const end = `${match[4].padStart(2, '0')}:${match[5]}`;

    return {
      dayOfWeek,
      start,
      end,
      startWeek,
      endWeek,
    };
  };

  // 检查时间段是否有重叠（时间）
  const isTimeOverlap = (slot1: TimeSlot, slot2: TimeSlot): boolean => {
    if (slot1.dayOfWeek !== slot2.dayOfWeek) return false;
    
    const toMinutes = (time: string): number => {
      const [h, m] = time.split(':').map(Number);
      return h * 60 + m;
    };

    const start1 = toMinutes(slot1.start);
    const end1 = toMinutes(slot1.end);
    const start2 = toMinutes(slot2.start);
    const end2 = toMinutes(slot2.end);

    // 检查时间段是否有交集
    return Math.max(start1, start2) < Math.min(end1, end2);
  };

  // 检查周数范围是否有重叠
  const isWeekOverlap = (slot1: TimeSlot, slot2: TimeSlot): boolean => {
    const startWeek1 = slot1.startWeek || 1;
    const endWeek1 = slot1.endWeek || 20;
    const startWeek2 = slot2.startWeek || 1;
    const endWeek2 = slot2.endWeek || 20;

    // 检查周数范围是否有交集
    return Math.max(startWeek1, startWeek2) <= Math.min(endWeek1, endWeek2);
  };

  // 检查时间冲突
  const checkTimeConflict = (
    newWeeks: string[], 
    newPeriods: string[], 
    newStartWeek: number, 
    newEndWeek: number
  ): { hasConflict: boolean; conflictInfo: string[] } => {
    const conflicts: string[] = [];

    // 将新申请的时间转换为时间段数组
    const newTimeSlots: TimeSlot[] = [];
    newWeeks.forEach(week => {
      newPeriods.forEach(period => {
        const periodOption = periodOptions.find(p => p.value === period);
        if (periodOption) {
          const timeStr = `${week} ${periodOption.time}`;
          const slot = parseTimeStringToSlot(timeStr, newStartWeek, newEndWeek);
          if (slot) {
            newTimeSlots.push(slot);
          }
        }
      });
    });

    // 检查与已通过课程的时间冲突
    myCourses.forEach((course: Course) => {
      course.timeSlots.forEach(existingSlot => {
        newTimeSlots.forEach(newSlot => {
          if (isTimeOverlap(newSlot, existingSlot) && isWeekOverlap(newSlot, existingSlot)) {
            const weekNames = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            conflicts.push(
              `与已通过课程"${course.name}"冲突：${weekNames[newSlot.dayOfWeek]} ${newSlot.start}-${newSlot.end}（第${newSlot.startWeek}-${newSlot.endWeek}周）`
            );
          }
        });
      });
    });

    // 检查与待审核/已通过申请课程的时间冲突
    appliedCourses.forEach(appliedCourse => {
      // 只检查已通过和待审核的申请
      if (appliedCourse.status === 'approved' || appliedCourse.status === 'pending') {
        const appliedSlots = appliedCourse.time.split(/[，,]/).map(timeStr => 
          parseTimeStringToSlot(timeStr.trim(), appliedCourse.startWeek, appliedCourse.endWeek)
        ).filter((slot): slot is TimeSlot => slot !== null);

        appliedSlots.forEach(appliedSlot => {
          newTimeSlots.forEach(newSlot => {
            if (isTimeOverlap(newSlot, appliedSlot) && isWeekOverlap(newSlot, appliedSlot)) {
              const weekNames = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
              conflicts.push(
                `与${appliedCourse.status === 'approved' ? '已通过' : '待审核'}申请课程"${appliedCourse.name}"冲突：${weekNames[newSlot.dayOfWeek]} ${newSlot.start}-${newSlot.end}（第${newSlot.startWeek}-${newSlot.endWeek}周）`
              );
            }
          });
        });
      }
    });

    return {
      hasConflict: conflicts.length > 0,
      conflictInfo: conflicts,
    };
  };

  // 将选择的星期和节次转换为时间字符串
  const convertTimeSlotsToString = (weeks: string[], periods: string[]): string => {
    if (!weeks || weeks.length === 0 || !periods || periods.length === 0) {
      return '';
    }

    const timeSlots: string[] = [];
    
    // 遍历每个星期和每个节次，生成所有组合
    weeks.forEach(week => {
      periods.forEach(period => {
        const periodOption = periodOptions.find(p => p.value === period);
        if (periodOption) {
          timeSlots.push(`${week} ${periodOption.time}`);
        }
      });
    });

    // 用逗号连接多个时间段
    return timeSlots.join('，');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      // 将选择的星期和节次转换为时间字符串
      const timeString = convertTimeSlotsToString(values.weeks || [], values.periods || []);
      
      if (!timeString) {
        message.error('请选择上课时间和节次');
        return;
      }

      // 检查时间冲突
      const conflictCheck = checkTimeConflict(
        values.weeks || [],
        values.periods || [],
        values.startWeek,
        values.endWeek
      );

      if (conflictCheck.hasConflict) {
        message.error('时间冲突！与已通过或待审核课程存在时间冲突，请重新选择上课时间');
        return;
      }

      applyCourseMutation.mutate({
        name: values.name,
        time: timeString,
        credit: values.credit,
        maxCapacity: values.maxCapacity,
        startWeek: values.startWeek,
        endWeek: values.endWeek,
      });
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const columns = [
    {
      title: '课程名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '上课时间',
      dataIndex: 'time',
      key: 'time',
    },
    {
      title: '学分',
      dataIndex: 'credit',
      key: 'credit',
      align: 'center' as const,
    },
    {
      title: '周数',
      key: 'weeks',
      align: 'center' as const,
      render: (_: any, record: any) => `第${record.startWeek}-${record.endWeek}周`,
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center' as const,
      render: (status: string) => {
        const statusMap: Record<string, { text: string; color: string }> = {
          'approved': { text: '已通过', color: 'green' },
          'pending': { text: '待审核', color: 'orange' },
          'rejected': { text: '已拒绝', color: 'red' },
        };
        const config = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center' as const,
      render: (_: any, record: any) => {
        // 只有待审核状态的申请可以取消
        if (record.status === 'pending') {
          return (
            <Popconfirm
              title="确定要取消申请吗？"
              description="取消后将无法恢复"
              onConfirm={() => cancelApplicationMutation.mutate(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" danger size="small">
                取消申请
              </Button>
            </Popconfirm>
          );
        }
        return '-';
      },
    },
  ];

  return (
    <div className="p-4 pb-24">
      <div className="text-xl font-semibold text-gray-800 mb-6">申请课程</div>
      
      {/* 主要内容：已申请课程列表 */}
      <Card 
        title={<span className="text-lg font-semibold text-gray-800">已申请课程</span>}
        className="shadow-md"
        bordered={false}
      >
        <Table
          dataSource={appliedCourses}
          rowKey="id"
          columns={columns}
          pagination={false}
        />
        {appliedCourses.length === 0 && (
          <div className="text-center py-8 text-gray-400">
            暂无申请记录
          </div>
        )}
      </Card>

      {/* 浮动按钮：申请新课程 */}
      <FloatButton
        icon={<FileAddOutlined />}
        type="primary"
        style={{ right: 24, bottom: 80, width: 60, height: 60 }}
        tooltip={<div style={{ textAlign: 'center' }}>申请新课程</div>}
        onClick={handleOpenModal}
        description="申请"
      />

      {/* 申请新课程Modal */}
      <Modal
        title="申请新课程"
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={handleCloseModal}
        confirmLoading={applyCourseMutation.isPending}
        okText="提交申请"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          className="mt-4"
        >
          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="课程名称"
              name="name"
              rules={[{ required: true, message: '请输入课程名称' }]}
            >
              <Input placeholder="请输入课程名称" />
            </Form.Item>

            <Form.Item
              label="学分"
              name="credit"
              rules={[
                { required: true, message: '请输入学分' },
                { type: 'number', min: 1, message: '学分至少为1' }
              ]}
            >
              <InputNumber 
                placeholder="请输入学分" 
                className="w-full"
                min={1}
              />
            </Form.Item>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="上课时间（星期）"
              name="weeks"
              rules={[{ required: true, message: '请选择上课时间' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择星期"
                options={weekOptions}
                maxTagCount="responsive"
              />
            </Form.Item>

            <Form.Item
              label="上课节次"
              name="periods"
              rules={[{ required: true, message: '请选择上课节次' }]}
            >
              <Select
                mode="multiple"
                placeholder="请选择节次"
                options={periodOptions.map(p => ({ label: p.label, value: p.value }))}
                maxTagCount="responsive"
              />
            </Form.Item>
          </div>

          <Form.Item
            label="选课人数上限"
            name="maxCapacity"
            rules={[
              { required: true, message: '请输入选课人数上限' },
              { type: 'number', min: 1, message: '人数上限至少为1' }
            ]}
          >
            <InputNumber 
              placeholder="请输入选课人数上限" 
              className="w-full"
              min={1}
            />
          </Form.Item>

          <div className="grid grid-cols-2 gap-4">
            <Form.Item
              label="开始周数"
              name="startWeek"
              rules={[
                { required: true, message: '请输入开始周数' },
                { type: 'number', min: 1, max: 20, message: '周数范围为1-20' }
              ]}
            >
              <InputNumber 
                placeholder="开始周数" 
                className="w-full"
                min={1}
                max={20}
              />
            </Form.Item>

            <Form.Item
              label="结束周数"
              name="endWeek"
              rules={[
                { required: true, message: '请输入结束周数' },
                { type: 'number', min: 1, max: 20, message: '周数范围为1-20' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    const startWeek = getFieldValue('startWeek');
                    if (!value || !startWeek || value >= startWeek) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('结束周数必须大于或等于开始周数'));
                  },
                }),
              ]}
            >
              <InputNumber 
                placeholder="结束周数" 
                className="w-full"
                min={1}
                max={20}
              />
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </div>
  );
}
